package com.tanhua.mongo.api;

import com.tanhua.api.MovementApi;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import com.tanhua.mongo.util.IdWorker;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class MovementApiImpl implements MovementApi {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private TimeLineService timeLineService;
    @Override
    public String publish(Movement movement) {
        //1.设置pid唯一标识
        movement.setPid(idWorker.getNextId("movement"));

        //2.保存动态数据
        mongoTemplate.save(movement);

//        //3.查询用户的好友信息
//        //封装查询条件
//        Query query = Query.query(Criteria.where("userId").is(movement.getUserId()));
//        //执行查询
//        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
//
//        try {
//            TimeUnit.SECONDS.sleep(20);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        //4.根据好友数据保存时间线数据
//        for (Friend friend : friendList) {
//            MovementTimeLine timeLine =new MovementTimeLine();
//            timeLine.setMovementId(movement.getId());
//            timeLine.setUserId(movement.getUserId());
//            timeLine.setFriendId(friend.getFriendId());
//            timeLine.setCreated(movement.getCreated());
//            mongoTemplate.save(timeLine);
//        }
        //异步执行保存时间线
        timeLineService.saveTimeLine(movement);

        //返回动态的主键id
        return movement.getId().toHexString();
    }


    //根据用户id分页查询动态数据  包括总记录数
    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        //1.封装查询条件
        Query query=Query.query(Criteria.where("userId").is(userId));
        //2.查询总记录数
        long count = mongoTemplate.count(query, Movement.class);
        //3.设置分页参数
        query.skip((page -1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //4.查询当前页的list
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        //封装pageResult并返回数据

        return new PageResult(page,pagesize, (int) count,movementList);
    }


    //查询好友动态, 不返回查询总记录数
    @Override
    public List<Movement> findFriendMovements(Long userId, Integer page, Integer pagesize) {
        //1.查询时间线表
        //设置查询条件
        Query query = Query.query(Criteria.where("friendId").is(userId));
        //设置分页  按照时间倒序排序
        query.skip((page - 1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        //执行查询
        List<MovementTimeLine> movementTimeLineList = mongoTemplate.find(query, MovementTimeLine.class);
        //2.根据时间线查询结果,获取动态ids
        List<ObjectId> movementIds = movementTimeLineList.stream()
                .map(MovementTimeLine::getMovementId)
                .collect(Collectors.toList());
        //3.根据动态id分页查询动态数据
        Query movementQuery =Query.query(Criteria.where("id").in(movementIds));
        List<Movement> movementList = mongoTemplate.find(movementQuery, Movement.class);
        //4.返回结果
        return movementList;
    }

    //随机获取count条数据
    @Override
    public List<Movement> randomMovement(int count) {
        //使用MongoDB的统计,实现随机获取
        //1.创建统计查询
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,Aggregation.sample(count));
        //2.执行统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //3.从统计结果里面获取随机动态数据
        return results.getMappedResults();
    }

    //根据pid查询动态
    @Override
    public List<Movement> findByPids(List<Long> pids) {
        //声明查询条件
        Query query = new Query(Criteria.where("pid").in(pids));

        //执行查询
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        //返回结果
        return movementList;
    }


    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(new ObjectId(movementId),Movement.class);
    }

    //根据用户id和审核状态,分页查询动态数据
    @Override
    public PageResult findMovementsByUid(Long uid, Integer state, Integer page, Integer pagesize) {
        //1.创建查询条件
        Criteria criteria = Criteria.where("userId").is(uid);
        if (state !=null){
            criteria.and("state").is(state);
        }
        Query query = Query.query(criteria);

        //2.根据条件查询总记录数
        long count = mongoTemplate.count(query, Movement.class);

        //3.设置分页参数
        query.skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        //4.根据条件分页查询
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);

        //5.封装分页对象 返回结果
        return new PageResult(page,pagesize, (int) count,movementList);
    }


    //根据动态的id 修改审核状态
    @Override
    public void updateState(String movementId, int state) {
        mongoTemplate.updateFirst(
                Query.query(Criteria.where("id").is(new ObjectId(movementId))),
                Update.update("state",state),
                Movement.class
        );
    }
}
